package com.xhy.documents_collection.controller.admin;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xhy.documents_collection.annotations.OperLog;
import com.xhy.documents_collection.enums.BusinessType;
import com.xhy.documents_collection.enums.ServiceType;
import com.xhy.documents_collection.holder.UserHolder;
import com.xhy.documents_collection.annotations.Authority;
import com.xhy.documents_collection.entity.PO.log.SysLog;
import com.xhy.documents_collection.entity.VO.AssignRoleVO;
import com.xhy.documents_collection.entity.VO.AuthorityVO;
import com.xhy.documents_collection.entity.PO.authority.Role;
import com.xhy.documents_collection.entity.PO.authority.RolePermission;
import com.xhy.documents_collection.entity.PO.authority.Tree;
import com.xhy.documents_collection.entity.PO.team.UserRole;
import com.xhy.documents_collection.service.authority.RolePermissionService;
import com.xhy.documents_collection.service.authority.RoleService;
import com.xhy.documents_collection.service.authority.UserRoleService;

import com.xhy.documents_collection.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;


import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author B站-xhyOVO
 * @since 2022-06-04
 */
@RestController
@RequestMapping("/authorize/role")
public class RoleController {

    @Autowired
    private RoleService roleService;


    @Autowired
    private RolePermissionService rolePermissionService;

    @Autowired
    private UserRoleService userRoleService;

    /**
     * 树形
     * @return
     */
    @GetMapping("/treeList")
    @Authority("permission:treeList")
    public List<Tree> treeList(){
        List<Tree> data = roleService.tree();
        return data;
    }

    /**
     * 给用户分配角色
     * 给用户分配角色前把之前的角色都删了
     * @param assignRoleVO
     * @return
     */
    @PostMapping("/assignRole")
    @Authority("user:assignRole")
    public R assignRole(@RequestBody AssignRoleVO assignRoleVO){

        return roleService.gaveRole(assignRoleVO);
    }

    /**
     * 获取用户角色
     * @param id
     * @return
     */
    @GetMapping("/getUserRole/{id}")
    @Authority("role:getRole")
    public List<Integer> getRole(@PathVariable Integer id){
        List<Integer> list = userRoleService.list(new QueryWrapper<UserRole>().eq("u_id", id).select("r_id"))
                .stream().map(UserRole::getRId).collect(Collectors.toList());
        return list;
    }

    /**
     * 初始化角色
     * @return
     */
    @GetMapping("/initRole")
    @Authority("role:initRole")
    public List<Map<String,Object>> initRole(){

        // 查出所有角色
        List<Map<String, Object>> list = roleService.list().stream()
                .map(role -> {
                    Map<String, Object> data = new HashMap<>();
                    data.put("value", role.getId());
                    data.put("title", role.getName());
                    return data;
                }).collect(Collectors.toList());

        return list;
    }


    /**
     * 角色列表
     * @param current
     * @param limit
     * @param name
     * @return
     */
    @GetMapping("/list")
    @Authority("role:list")
    public R list(@RequestParam(value = "page",defaultValue = "1") Long current,
                  @RequestParam(value = "limit",defaultValue = "15") Long limit,
                  @RequestParam(required = false) String name){
        QueryWrapper<Role> wrapper = new QueryWrapper<>();
        wrapper.like(!ObjectUtils.isEmpty(name),"name",name);
        Page<Role> page = roleService.page(new Page<>(current, limit), wrapper);

        return R.ok().data("data",page.getRecords()).count(page.getTotal());
    }

    /**
     * 添加角色
     * @param role
     * @return
     */
    @PostMapping
    @Authority("role:add")
    public R add(@RequestBody Role role){
        roleService.save(role);
        return R.ok();
    }

    /**
     * 修改角色
     * @param role
     * @return
     */
    @PutMapping
    @Authority("role:update")
    public R update(@RequestBody Role role){
        roleService.updateById(role);
        return R.ok();
    }

    /**
     * 删除角色
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    @Authority("role:delete")
    public R delete(@PathVariable String id){
        return roleService.removeRole(id);
    }


    /**
     * 给角色分配权限
     * @param authorityVO
     * @return
     * 给角色分配权限前先把该角色的权限都删了
     */
    @PostMapping("/authority")
    @Authority("role:authority")
    @OperLog(title = ServiceType.PERMISSION,businessType = BusinessType.GRANT)
    public R authority(@RequestBody AuthorityVO authorityVO){
        R r = roleService.gavePermission(authorityVO);

        return r;
    }

    /**
     * 获取角色权限
     * @param id
     * @return
     */
    @GetMapping("/getPermission/{id}")
    @Authority("role:getPermission")
    public Integer[] getPermission(@PathVariable Integer id){
        Integer[] list = rolePermissionService.list(new QueryWrapper<RolePermission>().eq("r_id", id).select("p_id"))
                .stream().map(RolePermission::getPId).toArray(Integer[]::new);
        return list;
    }

}

